package com.zhenyi.youqu.admin.index;

import java.util.List;

import com.jfinal.aop.Clear;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.youqu.common.model.YqGroup;
import com.youqu.common.model.YqProduct;
import com.youqu.common.model.YqShopUser;

public class GroupController extends YQAdminController {

	/**
	 * 显示团购列表,显示团是否完成,是否关闭,团内已支付人数(弹框/展开,头像,微信,订单号)
	 */
	@Override
	@Clear
	public void list() {
		super.list();
		YqShopUser user = getShopUser();
		Kv kv = getSimpleKv("productId", "isClosed", "isDone");
		SqlPara sqlPara = db.getSqlPara("YQAdminAllGroups", kv);
		Page<YqGroup> pages = YqGroup.dao.paginate(getPage(), getPageSize(), sqlPara);
		List<YqGroup> list = pages.getList();
		for (YqGroup group : list) {
			Kv kvUsers = Kv.by("groupId", group.getId());
			SqlPara spUsers = db.getSqlPara("YQAdminGroupUsers", kvUsers);
			List<Record> users = db.find(spUsers);
			group.put("users", users);
		}
		setRainbow(pages);
		setData("items", list);
		SqlPara spProducts = db.getSqlPara("YQProducts", Kv.by("appId", user.getAppId()));
		List<YqProduct> products = YqProduct.dao.find(spProducts);
		setData("products", products);
		render("/yq/admin/group/list.html");
	}

	/**
	 * 关闭团,切退款
	 */
	@Clear
	public void close() {
		Long groupId = getParaToLong("groupId");
		if (groupId == null) {
			renderFailure();
			return;
		}
		YqGroup group = YqGroup.dao.findById(groupId);
		if (group == null) {
			renderFailure();
			return;
		}
		group.closeAndRefund();
		renderSuccess();
	}

	public void user() {
		Long groupId = getParaToLong("groupId");
		Kv kv = Kv.by("groupId", groupId);
		SqlPara sqlPara = db.getSqlPara("YQFindGroupUser", kv);
		List<Record> users = db.find(sqlPara);
		setData("items", users);
		render("/yq/admin/group/user.html");
	}
}
